package com.cunshe.web;

import com.cunshe.common.*;
import com.cunshe.domain.*;
import com.cunshe.service.*;
import com.sunkee.commons.utils.ListUtils;
import com.sunkee.entity.page.Pageable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Email;
import java.util.*;

@Controller
@RequestMapping("/")
public class HomeController extends BaseController{

    @Autowired
    private NewsService newsService;
    @Autowired
    private CompanyProfileService companyProfileService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private DataDownService dataDownService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductImageService productImageService;
    @Autowired
    private HomeBannerService homeBannerService;
    @Autowired
    private SecondScreenService secondScreenService;
    @Autowired
    private CorporateStyleService corporateStyleService;
    @Autowired
    private MemorabiliaService memorabiliaService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private EmailAddressService emailAddressService;

    @ModelAttribute
    public void loadMenu(Model model) {
        List<Menu> menus = menuService.all();
        menus = (List<Menu>) ListUtils.list2Tree(menus);

        CompanyProfile companyProfile = companyProfileService.get();

        String lang = Optional.ofNullable(request.getSession().getAttribute("lang"))
                .map(Object::toString)
                .orElse(LangEnum.zh.name());
        Map<String, String> i18n = I18n.getI18n(lang);

        model.addAttribute("i18n", i18n);

        model.addAttribute("companyProfile", companyProfile);
        model.addAttribute("page", "");
        model.addAttribute("menus", menus);
    }

    /**
     * 首页
     */
    @GetMapping("")
    public String index(Model model) {
        List<HomeBanner> homeBanners = homeBannerService.all();
        List<SecondScreen> secondScreens = secondScreenService.top(3, 1);
        List<CorporateStyle> corporateStyles = corporateStyleService.getByType(2);
        List<Product> products = productService.top(6);

        model.addAttribute("products", products);
        model.addAttribute("corporateStyles", corporateStyles);
        model.addAttribute("secondScreens", secondScreens);
        model.addAttribute("homeBanners", homeBanners);
        model.addAttribute("page", "home");
        return "index";
    }

    private List<Menu> series(List<Menu> menus){
        for (Menu menu : menus) {
            if(menu.getId() == 2){
                return menu.getChildren();
            }
        }
        return null;
    }

    @GetMapping(value = "product")
    private String product(Model model){
        List<Menu> menus = (List<Menu>) model.getAttribute("menus");
        List<Menu> series = series(menus);

        model.addAttribute("series", series);
        return "product";
    }

    @GetMapping(value = "product_list_{id}")
    private String product_list(@PathVariable(value = "id") Long id, Model model){
        List<Menu> menus = (List<Menu>) model.getAttribute("menus");
        List<Menu> series = series(menus);

        Menu menu = getMenuById(id);
        List<Product> products = productService.list(Product.builder().category1(Long.toString(id)).build());

        model.addAttribute("series", series);
        model.addAttribute("products", products);
        model.addAttribute("menu", menu);
        return "product-list";
    }

    /**
     * 产品详情
     */
    @GetMapping(value = "product_detail_{id}")
    public String product_detail(@PathVariable(value = "id") Long id, Model model) {
        Product product = productService.get(id);
        if (product == null) {
            return null;
        }
        List<ProductImage> productImage = productImageService.getProductImage(id);
        String mainImage = "";
        if (!CollectionUtils.isEmpty(productImage)) {
            mainImage = productImage.get(0).getUrl();
        }
        List<Product> related = productService.list(Product.builder().category1(product.getCategory1()).build());

        List<DataDown> dataDowns = dataDownService.getByProductId(id);

        model.addAttribute("product", product);
        model.addAttribute("dataDowns", dataDowns);
        model.addAttribute("productImage", productImage);
        model.addAttribute("mainImage", mainImage);
        model.addAttribute("related", related);
        return "product-detail";
    }


    /**
     * 查询新闻
     * @param pageNo
     * @param type
     * @return
     */
    @GetMapping(value = "queryNew")
    @ResponseBody
    public ResponseVO<Pageable<News>> queryNew(@RequestParam("pageNo") int pageNo, @RequestParam("type") int type) {
        Pageable<News> pagelist = newsService.pagelist(pageNo, 6, News.builder().type(type).build());
        return ResponseVO.success(pagelist);
    }

    /**
     * 资料下载
     */
    @GetMapping(value = "download")
    public String download(Model model) {
        List<DataDown> dataDowns = dataDownService.all();
        Menu menu = getMenuById(5L);

        model.addAttribute("menu", menu);
        model.addAttribute("dataDowns", dataDowns);
        return "download";
    }

    private Menu getMenuById(Long id){
        List<Menu> menus = menuService.list(Menu.builder().build().setId(id));
        return menus.stream()
                .filter(var -> var.getId().equals(id))
                .findFirst()
                .orElse(null);
    }

    /**
     * 新闻
     */
    @GetMapping(value = {"news", "news"})
    public String news(Model model) {
        Menu menu = getMenuById(3L);

        List<News> news1 = newsService.list(News.builder().type(1).build());
        List<News> news2 = newsService.list(News.builder().type(2).build());

        model.addAttribute("news1", news1);
        model.addAttribute("news2", news2);
        model.addAttribute("menu", menu);
        return "new-list";
    }

    /**
     * 新闻详情
     */
    @GetMapping(value = "news_detail_{id}")
    public String news_detail(@PathVariable(value = "id") Long id, Model model) {
        News news = newsService.get(id);

        model.addAttribute("news", news);
        return "new-detail";
    }

    /**
     * 关于我们
     */
    @GetMapping(value = "about_us")
    public String about_us(Model model) {
        List<CorporateStyle> corporateStyles1 = corporateStyleService.getByType(1);
        List<CorporateStyle> honors = corporateStyleService.getByType(3);
        List<Memorabilia> memorabilias = memorabiliaService.list();
        List<SecondScreen> secondScreens = secondScreenService.top(4, 2);

        model.addAttribute("secondScreens", secondScreens);
        model.addAttribute("memorabilias", memorabilias);
        model.addAttribute("honors", honors);
        model.addAttribute("corporateStyles", corporateStyles1);
        return "about-us";
    }

    /**
     * 联系我们
     */
    @GetMapping(value = "contact_us")
    public String contact_us(Model model) {
        List<Office> offices = officeService.list();

        model.addAttribute("offices", offices);
        return "contact-us";
    }

    /**
     * 切换语言
     * @param lang
     * @param request
     * @return
     */
    @GetMapping(value = "setLanguage")
    public String lang(@RequestParam("lang") LangEnum lang, HttpServletRequest request){
        System.out.println(lang);
        request.getSession().setAttribute("lang", lang.name());
        return "redirect:/";
    }

    @PostMapping(value = "subscription")
    @ResponseBody
    public ResponseVO subscription(@RequestParam("email") String email) {
        if(email.length() == 0 || email.length() > 255){
            return ResponseVO.success();
        }
        emailAddressService.insert(EmailAddress.builder().email(email).build());
        return ResponseVO.success();
    }

}
